<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\common\model\Authentication;
use app\common\model\CaptainApplication;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Hook;

class AuthenticationManager extends BaseManager
{

    /**
     * 实名认证
     * @param int $userId 用户uid
     * @param string $name 真实姓名
     * @param string $idCard 身份证
     * @param string $mobile 手机号
     * @param array $response 三方认证结果
     * @param bool $trans 是否开启事务
     * @return array
     */
    public static function AuthRealName(int $userId, string $name,string $idCard,string $mobile,array $response=[],bool $trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            $Authentication = Authentication::where('user_id',$userId)->order('id desc')->find();
            if ($Authentication){
                throw new Exception('您已实名认证');
            }

            Authentication::create([
                'user_id' => $userId,
                'real_name' => $name,
                'id_card' => $idCard,
                'mobile' => $mobile,
                'response' => serialize($response),
                'create_time' => time(),
                'update_time' => time()
            ]);
            $year = substr($idCard,6,4);
            $month = substr($idCard,10,2);
            $day = substr($idCard,12,2);
            $birthday = $year.'-'.$month.'-'.$day;
            User::update(['is_authentication'=>User::IS_AUTHENTICATION_YES,'birthday'=>$birthday],['id'=>$userId]);

            $user = User::get($userId);
            if ($user){
                Hook::listen('register_success',$user);
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }
}